#!/bin/bash

# Queue Admin 部署脚本
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 函数：打印彩色消息
print_message() {
    echo -e "${2}${1}${NC}"
}

# 显示帮助信息
show_help() {
    echo "Queue Admin 部署脚本"
    echo ""
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  start     启动所有服务"
    echo "  stop      停止所有服务"
    echo "  restart   重启所有服务"
    echo "  status    查看服务状态"
    echo "  logs      查看服务日志"
    echo "  dev       启动开发环境"
    echo "  build     构建并启动服务"
    echo "  clean     清理所有容器和数据"
    echo "  backup    备份数据"
    echo "  restore   恢复数据"
    echo "  help      显示此帮助信息"
}

# 检查服务状态
check_services() {
    print_message "📊 检查服务状态..." $BLUE
    docker-compose ps
}

# 查看日志
view_logs() {
    if [ -n "$2" ]; then
        print_message "📋 查看 $2 服务日志..." $BLUE
        docker-compose logs -f "$2"
    else
        print_message "📋 查看所有服务日志..." $BLUE
        docker-compose logs -f
    fi
}

# 启动服务
start_services() {
    print_message "🚀 启动 Queue Admin 服务..." $GREEN
    
    # 创建必要的目录
    mkdir -p logs
    mkdir -p docker/mysql
    
    # 启动服务
    docker-compose up -d
    
    print_message "⏳ 等待服务启动..." $YELLOW
    sleep 10
    
    # 检查服务状态
    check_services
    
    print_message "✅ 服务启动完成！" $GREEN
    print_message "🌐 访问地址:" $BLUE
    echo "  前端: http://localhost"
    echo "  后端: http://localhost:8080"
    echo "  MySQL: localhost:3306"
    echo "  Redis: localhost:6379"
}

# 停止服务
stop_services() {
    print_message "🛑 停止 Queue Admin 服务..." $YELLOW
    docker-compose down
    print_message "✅ 服务已停止" $GREEN
}

# 重启服务
restart_services() {
    print_message "🔄 重启 Queue Admin 服务..." $YELLOW
    docker-compose restart
    print_message "✅ 服务重启完成" $GREEN
}

# 启动开发环境
start_dev() {
    print_message "🛠️  启动开发环境..." $BLUE
    docker-compose -f docker-compose.dev.yml up -d
    
    print_message "✅ 开发环境启动完成！" $GREEN
    print_message "📋 开发环境信息:" $BLUE
    echo "  MySQL: localhost:3306"
    echo "  Redis: localhost:6379"
    echo "  Kafka: localhost:9092"
    echo "  RabbitMQ: localhost:5672 (管理界面: http://localhost:15672)"
    echo ""
    echo "现在可以在本地运行应用:"
    echo "  后端: cd server && mvn spring-boot:run"
    echo "  前端: cd webapp && npm run dev"
}

# 构建并启动
build_and_start() {
    print_message "🔨 构建并启动服务..." $BLUE
    ./build.sh
    start_services
}

# 清理所有数据
clean_all() {
    print_message "⚠️  这将删除所有容器、镜像和数据！" $RED
    read -p "确定要继续吗？(y/N): " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        print_message "🧹 清理所有数据..." $YELLOW
        docker-compose down -v --rmi all --remove-orphans
        docker-compose -f docker-compose.dev.yml down -v --rmi all --remove-orphans
        docker system prune -f
        print_message "✅ 清理完成" $GREEN
    else
        print_message "❌ 取消清理操作" $YELLOW
    fi
}

# 备份数据
backup_data() {
    print_message "💾 备份数据..." $BLUE
    
    BACKUP_DIR="backup/$(date +%Y%m%d_%H%M%S)"
    mkdir -p "$BACKUP_DIR"
    
    # 备份MySQL数据
    docker-compose exec -T mysql mysqldump -u root -proot queue_admin > "$BACKUP_DIR/mysql_backup.sql"
    
    # 备份Redis数据
    docker-compose exec -T redis redis-cli BGSAVE
    docker cp queue-admin-redis:/data/dump.rdb "$BACKUP_DIR/redis_backup.rdb"
    
    # 备份配置文件
    cp docker-compose.yml "$BACKUP_DIR/"
    cp -r docker "$BACKUP_DIR/"
    
    print_message "✅ 数据备份完成: $BACKUP_DIR" $GREEN
}

# 恢复数据
restore_data() {
    if [ -z "$2" ]; then
        print_message "❌ 请指定备份目录" $RED
        echo "用法: $0 restore <backup_directory>"
        exit 1
    fi
    
    BACKUP_DIR="$2"
    if [ ! -d "$BACKUP_DIR" ]; then
        print_message "❌ 备份目录不存在: $BACKUP_DIR" $RED
        exit 1
    fi
    
    print_message "📥 恢复数据..." $BLUE
    
    # 恢复MySQL数据
    if [ -f "$BACKUP_DIR/mysql_backup.sql" ]; then
        docker-compose exec -T mysql mysql -u root -proot queue_admin < "$BACKUP_DIR/mysql_backup.sql"
        print_message "✅ MySQL数据恢复完成" $GREEN
    fi
    
    # 恢复Redis数据
    if [ -f "$BACKUP_DIR/redis_backup.rdb" ]; then
        docker-compose stop redis
        docker cp "$BACKUP_DIR/redis_backup.rdb" queue-admin-redis:/data/dump.rdb
        docker-compose start redis
        print_message "✅ Redis数据恢复完成" $GREEN
    fi
    
    print_message "✅ 数据恢复完成" $GREEN
}

# 主逻辑
case "$1" in
    start)
        start_services
        ;;
    stop)
        stop_services
        ;;
    restart)
        restart_services
        ;;
    status)
        check_services
        ;;
    logs)
        view_logs "$@"
        ;;
    dev)
        start_dev
        ;;
    build)
        build_and_start
        ;;
    clean)
        clean_all
        ;;
    backup)
        backup_data
        ;;
    restore)
        restore_data "$@"
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        print_message "❌ 未知命令: $1" $RED
        echo ""
        show_help
        exit 1
        ;;
esac
